package com.pucong.gitee.database.backup.business.sys.service;

import com.pucong.gitee.database.backup.common.entity.sys.authorize.AuthorizeInfo;
import com.pucong.gitee.database.backup.common.entity.sys.authorize.AuthorizeResult;
import com.pucong.gitee.database.backup.common.entity.sys.authorize.AuthorizeResultDate;
import com.pucong.gitee.database.backup.configuration.authorize.LicenseAuth;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Calendar;
import java.util.Date;

@Service
@Slf4j
public class SysLicenceServiceImpl implements SysLicenceService {

    @Override
    public AuthorizeResult isAuthorize() {
        AuthorizeResult check = LicenseAuth.check();
        return check;
    }

    @Override
    public AuthorizeInfo getAuthorizeInfo() {
        AuthorizeInfo licenseObject = LicenseAuth.getLicenseObject();
        return licenseObject;
    }

    @Override
    public AuthorizeResultDate isAuthorizeExpireDate() {
        AuthorizeResultDate authorizeResultDate = new AuthorizeResultDate();
        AuthorizeInfo licenseObject = LicenseAuth.getLicenseObject();
        Date expireDate = licenseObject.getExpireDate();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date()); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        Date time = calendar.getTime();

        if(time.getTime() > expireDate.getTime()){
            authorizeResultDate.setSuccess(true);
        }else{
            authorizeResultDate.setSuccess(false);
        }
        authorizeResultDate.setSuccess(false);
        authorizeResultDate.setExpireDate(expireDate);
        return authorizeResultDate;
    }

    private String getFileContent(MultipartFile file) {
        BufferedReader reader = null;
        String ans = "";
        try {
            Reader read = new InputStreamReader(file.getInputStream(), "UTF8");
            reader = new BufferedReader(read);
            String tmpString = null;
            //一行一行的读取文件里面的内容
            while ((tmpString = reader.readLine()) != null) {
                ans += tmpString;//保存在ans里面
            }
            if (ans == null || ans == "") {
                throw new BusinessException("文件内容为空！");
            }
        } catch (IOException e) {
            log.error("异常", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    log.error("异常", e1);
                }
            }
        }
        return ans;
    }
}
